﻿var waitDialog;

// This fucntion shows modal dialog with page of "dialogUrl" URL
// "source" is passed like "source" query parameter
// "listID" is passed like "listid" query parameter
// "selectedItems" is passed like "items" query parameter
// If don't set "heightDialog" dialog will be autosized
function ShowDialog(dialogUrl, source, listID, selectedItems, heightDialog, allowMaximize)
{
	if (listID != null && listID != "")
	{
		dialogUrl = EnsureQuestionMark(dialogUrl);
		dialogUrl = dialogUrl + "&listid=" + listID;
	}

	if (selectedItems != null && selectedItems.length > 0)
	{
		dialogUrl = EnsureQuestionMark(dialogUrl);
		var items = "";
		for (var i = 0; i < selectedItems.length; i++)
		{
			var item = selectedItems[i];
			items = items + item.id + ",";
		}
		dialogUrl = dialogUrl + "&items=" + items;
	}

	if (source != null && source != "")
	{
		dialogUrl = EnsureQuestionMark(dialogUrl);
		dialogUrl = dialogUrl + "&Source=" + source;
	}

	if (allowMaximize == null)
	{
		allowMaximize = false;
	}

	var options = {
		url: dialogUrl, 
		allowMaximize: allowMaximize,
		showClose: true,
		autoSize: true,
		dialogReturnValueCallback: callbackDialog,
		height: heightDialog
	};
	
	waitDialog = SP.UI.ModalDialog.showModalDialog(options);
}

// This function ensures that url has question mark
function EnsureQuestionMark(url)
{
	var index = url.indexOf("?");
	if (index == -1)
		url = url + "?";

	return url;
}

// This is callback function for shown dialog
function callbackDialog(result, response)
{
	if (response != null && response.url != null)
	{
		if (response.showInDialog)
		{
			ShowDialog(response.url);
		}
		else
		{
			window.location = response.url;
		}
		return;
	}
	
	SP.UI.ModalDialog.RefreshPage(1);
}

function getQueryParam(key, default_)
{
	if (default_ == null) default_ = "";
	key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if (qs == null)
		return default_;
	else
		return qs[1];
}